package com.repu.pubmedspider.Controller;

import com.repu.pubmedspider.Utils.Constant;
import com.repu.pubmedspider.Entity.UserEntity;
import com.repu.pubmedspider.Service.UserService;
import com.repu.pubmedspider.Utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;


@RestController("user")
@RequestMapping(path = Constant.BASE_PATH_PERFIX + "/user")
// 表示标识这个类是swagger的资源
@Api(value = "UserController", tags = {"登录接口模块"})
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping(value = "/test", method = RequestMethod.GET)
    @ResponseBody
    //表示一个http请求的操作
    @ApiOperation(value = "test", httpMethod = "GET", produces = "application/json")
    //@ApiImplicitParams用于方法，包含多个@ApiImplicitParam表示单独的请求参数
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "产品ID", required = true, paramType = "path")})
    public UserEntity hello() {
        UserEntity userEntity = userService.user();
        return userEntity;
    }


    @ApiOperation(value = "登录", notes = "通过用户名和密码登录系统") //配置方法操作在swagger中的名和曾 notes为备注
    @PostMapping(value = "/login")
    public String login(@RequestBody UserEntity user) {
        if (user == null) {
            return "用户名或密码为空！";
        }
        UserEntity loginUser = userService.userLogin(user);
        if (loginUser == null) {
            return "用户名或密码错误！";
        }

        //生成token（用户拿着这个token+请求返回给服务端，服务端匹配token，如果匹配上了则处理用户发来的请求，如果匹配不上则用户验证失败不处理请求）
        String jwt = JwtUtil.createToken(user.getAccount());
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return ResponseEntity.ok(loginUser).toString() + map;
    }

    @ApiOperation(value = "测试", notes = "通过用户名和密码测试token")
    @PostMapping(value = "test")
    public String testToken(@RequestBody UserEntity user){
        return user.toString();
    }




}
